package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.pojo.Book;
import com.example.pojo.MyPageData;
import com.example.pojo.Result;
import com.example.pojo.VO.BookVO;
import com.example.service.BookService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    //根据id查询书籍信息
    @GetMapping("/{id}")
    public Result<Book> getBookById(@PathVariable("id") Integer id) {
        Book book = bookService.getById(1);
        return Result.ok(book);
    }

    //获取所有书籍的信息
    @GetMapping("/all")
    public Result<List<Book>> getAllBook() {
        List<Book> list = bookService.list();
        return Result.ok(list);

    }

//    @ApiOperation("根据类型id查询图书")
    @PostMapping("/getBookByTypeId/{typeId}/{pageNum}/{pageSize}")
    public Result getBookType(
            @PathVariable("typeId") Integer typeId,
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize) {
        //创建分页对象
        Page<Book> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type_id", typeId);
        bookService.page(page, queryWrapper);
        List<Book> books = page.getRecords();
        List<BookVO> vos = new ArrayList<>();
        books.forEach(book -> {
            BookVO bookVO = new BookVO();
            BeanUtils.copyProperties(book, bookVO);
            vos.add(bookVO);
        });
        MyPageData myPageData = new MyPageData(page.getTotal(), vos);
        return Result.ok(myPageData);
    }

}
